<template>
  <div class="chat-container">
    <h1 class="chat-title">Video Chat</h1>
    <div class="video-wrapper">
      <video ref="localVideo" class="video" autoplay muted></video>
      <video ref="remoteVideo" class="video" autoplay></video>
    </div>
    <div class="control-panel">
      <div class="user-input">
        <input v-model="userId" placeholder="User ID" class="input-field" />
        <button @click="startVideoChat" class="start-chat-btn">Start Video Chat</button>
      </div>
      <div class="message-input">
        <input v-model="message" placeholder="Message" class="input-field" />
        <button @click="sendMessage" class="send-message-btn">Send Message</button>
      </div>
      <p class="response-message">{{ response }}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import socket from "sockjs-client/lib/transport/iframe";
export default {
  data() {
    return {
      localStream: null,
      remoteStream: null,
      peerConnection: null,
      peerStarted: false,
      userId: '2',
      message: '',
      response: '',
      socket: null,
      socketUrl: '',
      socketRead: false,
    };
  },
  mounted() {
    const userid = Math.round(Math.random() * 1000);
    this.socketUrl = `ws://localhost:8080/video/msgServer/${userid}`;
    this.socket = new WebSocket(this.socketUrl);

    this.socket.onopen = () => {
      console.log('成功连接到服务器...');
      this.socketRead = true;
    };

    this.socket.onclose = (e) => {
      console.log('与服务器连接关闭: ' + e.code);
      this.socketRead = false;
    };

    function determineSdpType(sdp) {
      // 这是一个非常简化的示例，实际上可能需要根据具体的 SDP 格式进行调整
      // 注意：这种方法并不总是可靠的，因为 SDP 格式可能会有所不同
      if (sdp.includes('a=ice-lite')) {
        // 假设包含 'a=ice-lite' 的是 answer
        return 'answer';
      } else {
        // 否则，假设它是 offer
        return 'offer';
      }
    }

// 完整的 WebSocket 消息处理函数
    this.socket.onmessage = (event) => {
      let evt;
      try {
        evt = JSON.parse(event.data);
        // 处理 JSON 消息...（如果有的话）
      } catch (jsonError) {
        console.warn('Failed to parse JSON:', jsonError);

        if (event.data.startsWith('v=')) {
          // 处理 SDP 数据
          const sdpData = event.data;
          let sdpType = determineSdpType(sdpData);

          const sessionDescription = new RTCSessionDescription({
            type: sdpType,
            sdp: sdpData
          });

          if (sdpType === 'offer') {
            this.peerConnection.setRemoteDescription(sessionDescription)
              .then(() => this.peerConnection.createAnswer())
              .then(answer => this.peerConnection.setLocalDescription(answer))
              .then(() => {
                // 发送 answer 给远端（这里需要实现发送逻辑）
                // 例如：this.socket.send(JSON.stringify({ sdp: this.peerConnection.localDescription }));
              })
              .catch(error => console.error('处理 offer 失败:', error));
          } else if (sdpType === 'answer') {
            this.peerConnection.setRemoteDescription(sessionDescription)
              .catch(error => console.error('设置远程 answer 描述失败:', error));
          }
        } else {
          console.warn('Received unknown data format:', event.data);
        }
      }
    };
  },
  methods: {

    generateUserId() {
      return Math.round(Math.random() * 1000).toString();
    },
    startVideoChat() {
      if (!this.localStream) {
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
          .then((stream) => {
            this.localStream = stream;
            this.$refs.localVideo.srcObject = stream;
            if (!this.peerStarted) {
              this.peerStarted = true;
              this.sendOffer(); // 发送 Offer 以开始视频聊天
            }
          })
          .catch((error) => {
            // 更详细的错误处理
            console.error('获取媒体设备时发生错误:', error);
            if (error.name === 'NotAllowedError') {
              alert('您未授予访问摄像头和麦克风的权限，请检查浏览器权限设置。');
            } else if (error.name === 'NotFoundError' || error.name === 'DevicesNotFoundError') {
              alert('未找到摄像头或麦克风设备，请检查设备连接状态。');
            } else if (error.name === 'NotAllowedError' || error.name === 'PermissionDeniedError') {
              alert('权限被拒绝，请允许访问摄像头和麦克风。');
            } else {
              alert('发生了一个未知错误，请尝试刷新页面或更新浏览器。');
            }
          });
      } else {
        alert('视频和音频已经开启');
      }
    },
    sendOffer() {
      const pcConfig = { "iceServers": [] };
      this.peerConnection = new RTCPeerConnection(pcConfig);

      this.peerConnection.onicecandidate = (evt) => {
        if (evt.candidate) {
          this.sendCandidate(evt.candidate);
        }
      };

      this.peerConnection.ontrack = (event) => {
        this.remoteStream = event.streams[0];
        this.$refs.remoteVideo.srcObject = this.remoteStream;
      };

      this.peerConnection.addStream(this.localStream);

      this.peerConnection.createOffer()
        .then((sessionDescription) => {
          this.peerConnection.setLocalDescription(sessionDescription);
          this.sendSDP(sessionDescription);
        })
        .catch((err) => {
          console.log('创建Offer失败');
        });
    },
    sendSDP(sdp) {
      const text = JSON.stringify({ type: sdp.type, sdp: sdp.sdp });
      this.socket.send(text);
    },
    sendCandidate(candidate) {
      const text = JSON.stringify({
        type: 'candidate',
        sdpMLineIndex: candidate.sdpMLineIndex,
        sdpMid: candidate.sdpMid,
        candidate: candidate.candidate,
      });
      this.socket.send(text);
    },
    onOffer(evt) {
      if (this.peerConnection) {
        console.error('peerConnection已存在!');
        return;
      }
      // if (this.peerConnection) {
      //   this.peerConnection.close();
      //   this.peerConnection = null;
      // }
      this.peerConnection = new RTCPeerConnection({ "iceServers": [] });
      this.peerConnection.onicecandidate = (evt) => {
        if (evt.candidate) {
          this.sendCandidate(evt.candidate);
        }
      };

      this.peerConnection.ontrack = (event) => {
        this.remoteStream = event.streams[0];
        this.$refs.remoteVideo.srcObject = this.remoteStream;
      };
      // this.peerConnection.setRemoteDescription(new RTCSessionDescription(evt.sdp));
      // this.sendAnswer(evt);
      // this.peerStarted = true;

      this.peerConnection.setRemoteDescription(new RTCSessionDescription({
        type: evt.sdp.type,  // 确保这里有正确的类型，如 "offer"
        sdp: evt.sdp.sdp     // 确保这里有正确的 SDP 字符串
      }));
    },
    sendAnswer(evt) {
      this.peerConnection.createAnswer()
        .then((sessionDescription) => {
          this.peerConnection.setLocalDescription(sessionDescription);
          this.sendSDP(sessionDescription);
        })
        .catch((err) => {
          console.log('创建Answer失败');
        });
    },
    onAnswer(evt) {
      // this.peerConnection.setRemoteDescription(new RTCSessionDescription(evt.sdp));
      this.peerConnection.setRemoteDescription(new RTCSessionDescription({
        type: evt.sdp.type,  // 确保这里有正确的类型，如 "offer"
        sdp: evt.sdp.sdp     // 确保这里有正确的 SDP 字符串
      }));
    },
    onCandidate(evt) {
      const candidate = {
        sdpMLineIndex: evt.sdpMLineIndex,
        sdpMid: evt.sdpMid,
        candidate: evt.candidate,
      };
      // 创建一个新的RTCIceCandidate对象并添加到peerConnection中
      this.peerConnection.addIceCandidate(new RTCIceCandidate(candidate))
        .catch((error) => {
          console.error('添加ICE候选失败:', error);
        });
    },
    stop() {
      this.peerConnection.close();
      this.peerConnection = null;
      this.peerStarted = false;
      this.localStream.getTracks().forEach((track) => track.stop());
      this.localStream = null;
      if (this.remoteStream) {
        this.remoteStream.getTracks().forEach((track) => track.stop());
        this.remoteStream = null;
      }
    },
    sendMessage() {
      if (this.userId && this.message) {
        axios.post(`/dev-api/video/api/sendMessage`, { userId: this.userId, message: this.message })
          .then((response) => {
            console.log('Message sent:', response.data);
            this.message = '';
          })
          .catch((error) => {
            console.error('Error sending message:', error);
          });
      } else {
        alert('Please enter both User ID and Message');
      }
    },
  },
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f0f0f0;
  padding: 20px;
}

.chat-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.video-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  max-width: 800px;
  margin-bottom: 30px;
}

.video {
  width: 45%;
  max-width: 400px;
  border-radius: 10px;
  background-color: #000;
}

.control-panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 800px;
}

.user-input, .message-input {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 15px;
}

.input-field {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 16px;
}

.start-chat-btn, .send-message-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #007bff;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
}

.start-chat-btn:hover, .send-message-btn:hover {
  background-color: #0056b3;
}

.response-message {
  font-size: 16px;
  color: #333;
  text-align: center;
  margin-top: 20px;
}
</style>
